package com.zhoug.common3.behaviors;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.google.android.material.snackbar.Snackbar;
import com.zhoug.common3.utils.LogUtils;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

/**
 * 用于解决显示Snackbar时遮住布局底部的bug
 * app:layout_behavior="@string/common_snackbar_behavior"
 * @Author 35574
 * @Date 2021/3/26
 * @Description
 */
public class SnackbarBehavior extends CoordinatorLayout.Behavior<View> {
    private static final String TAG = ">>>SnackBarBehavior";
    private static final boolean DEBUG = false;
    private float mSnackbarTranslationY = 0;

    public SnackbarBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (DEBUG) {
            LogUtils.d(TAG, "SnackBarBehavior create");
        }
    }


    /**
     * 确定使用Behavior的View要依赖的View的类型
     *
     * @param parent
     * @param child
     * @param dependency
     * @return
     */
    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        boolean b = dependency instanceof Snackbar.SnackbarLayout;
        if (b && mSnackbarTranslationY == 0) {
            mSnackbarTranslationY = dependency.getTranslationY();
            if (DEBUG) {
                LogUtils.d(TAG, "layoutDependsOn:child=" + child);
                LogUtils.d(TAG, "layoutDependsOn:mSnackbarTranslationY=" + mSnackbarTranslationY);
            }
        }
        return b;
    }

    /**
     * 当被依赖的View状态改变时回调
     *
     * @param parent
     * @param child
     * @param dependency
     * @return
     */
    @Override
    public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        float translationY = dependency.getTranslationY();
        if (DEBUG) {
            LogUtils.d(TAG, "onDependentViewChanged:translationY=" + translationY);
        }
        child.setTranslationY(translationY - mSnackbarTranslationY);
        return super.onDependentViewChanged(parent, child, dependency);
    }

}
